package com.sunchis.demo.util.jgroup;

import java.io.InputStream;

import org.jgroups.JChannel;
import org.jgroups.Message;

public class JGroupAgent {
	private JChannel jChannel;
	
	public JGroupAgent() throws Exception {
		System.setProperty("java.net.preferIPv4Stack", "true");
		
		InputStream confStream = this.getClass().getResourceAsStream("/udp.xml");
		jChannel = new JChannel(confStream);
		start();
		
		String clusterName = jChannel.getClusterName();
		if (clusterName != null) {
			System.out.println("成功加入到组【" + clusterName + "】中");
		}
	}
	
	private void start() {
		try {
			jChannel.setReceiver(new ReceiverMessage()); // 添加接收消息监听器
			jChannel.connect("mgt");
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("加入组播组失败！");
		}
	}
	
	public void sendMessage(String msg) throws Exception {
		Message message = new Message(null, null, msg);
		jChannel.send(message);
	}

	public JChannel getjChannel() {
		return jChannel;
	}
}
